package com.swust.inputbox;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson2.JSON;

import java.util.ArrayList;
import java.util.List;

public class SimpleActivity extends AppCompatActivity {
    private static final String TAG = "--->";

    private EditText searchEditText;
    private ImageButton clearButton;
    private ImageButton searchButton;
    private RecyclerView historyListView;
    private CorsUsernameAdapter historyAdapter;
    private List<String> searchHistory;
    private DatabaseHelper databaseHelper;

    @SuppressLint("WrongViewCast")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_simple);

        // 初始化视图组件
        searchEditText = findViewById(R.id.searchEditText);
        clearButton = findViewById(R.id.clearButton);
        searchButton = findViewById(R.id.searchButton);
        historyListView = findViewById(R.id.historyListView);

        // 初始化搜索历史列表
        databaseHelper = new DatabaseHelper(this);
        searchHistory = new ArrayList<>(databaseHelper.getAllSearchHistory());
        Log.i(TAG, "历史数据:) " + JSON.toJSONString(searchHistory));
//        historyAdapter = new ArrayAdapter<>(this,
//                R.layout.history_item,
//                R.id.historyItemText,
//                new ArrayList<>(searchHistory));
//        historyListView.setAdapter(historyAdapter);
        historyListView.setLayoutManager(new LinearLayoutManager(this));
        historyAdapter = new CorsUsernameAdapter(this, new ArrayList<>(searchHistory));
        historyListView.setAdapter(historyAdapter);

        // 设置文本变化监听器
        searchEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0) {
                    clearButton.setVisibility(View.VISIBLE);
                    // 显示包含当前输入的历史记录
                    List<String> filteredHistory = new ArrayList<>();
                    for (String history : searchHistory) {
                        if (history.toLowerCase().contains(s.toString().toLowerCase())) {
                            filteredHistory.add(history);
                        }
                    }
                    Log.i(TAG, "搜索字符:) " + s);
                    Log.i(TAG, "searchHistory:) " + searchHistory);
                    Log.i(TAG, "filteredHistory:) " + filteredHistory);
                    historyAdapter.setDataList(filteredHistory);
                    historyAdapter.notifyDataSetChanged();
                    historyListView.setVisibility(View.VISIBLE);
                } else {
                    clearButton.setVisibility(View.GONE);
                    // 显示全部历史记录
                    historyAdapter.setDataList(searchHistory);
                    historyAdapter.notifyDataSetChanged();
                    historyListView.setVisibility(searchHistory.isEmpty() ? View.GONE : View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        // 清空输入框
        clearButton.setOnClickListener(v -> searchEditText.setText(""));

        // 执行搜索
        searchButton.setOnClickListener(v -> performSearch());

//        // 点击历史记录项
//        historyListView.setOnItemClickListener((parent, view, position, id) -> {
//            String selectedHistory = historyAdapter.getItem(position);
//            searchEditText.setText(selectedHistory);
//            searchEditText.setSelection(selectedHistory.length());
//            historyListView.setVisibility(View.GONE);
//        });
//
//        // 长按删除历史记录
//        historyListView.setOnItemLongClickListener((parent, view, position, id) -> {
//            String historyItem = historyAdapter.getItem(position);
//            databaseHelper.deleteSearchHistory(historyItem);
//            searchHistory.remove(historyItem);
//            historyAdapter.notifyDataSetChanged();
//            historyListView.setVisibility(searchHistory.isEmpty() ? View.GONE : View.VISIBLE);
//            Toast.makeText(SimpleActivity.this, "已删除该历史记录", Toast.LENGTH_SHORT).show();
//            return true;
//        });
    }

    private void performSearch() {
        String query = searchEditText.getText().toString().trim();
        if (!query.isEmpty()) {
            // 保存搜索历史
            if (!searchHistory.contains(query)) {
                databaseHelper.addSearchHistory(query);
                searchHistory.add(0, query); // 添加到列表开头
                historyAdapter.notifyDataSetChanged();
            }
            // 执行搜索操作
            Toast.makeText(this, "搜索: " + query, Toast.LENGTH_SHORT).show();
            historyListView.setVisibility(View.GONE);
        }
    }

    @Override
    public void onBackPressed() {
        if (historyListView.getVisibility() == View.VISIBLE) {
            historyListView.setVisibility(View.GONE);
        } else {
            super.onBackPressed();
        }
    }
}